package com.zzy.lean_mqtt.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Service
public class MqttSenderService {

    @Autowired
    private MqttPahoMessageHandler mqttOutbound;

    public void sendMessage(String topic, String payload) {
        // 构建消息，指定主题和内容
        Message<String> message = MessageBuilder.withPayload(payload)
                .setHeader(MqttHeaders.TOPIC, topic)
                .build();
        // 发送消息
        mqttOutbound.handleMessage(message);
        System.out.println("消息已发送 -> 主题: " + topic + ", 内容: " + payload);
    }
}